<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ include file="/taglibs.jsp"%>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c-rt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@page import="com.yaodian100.core.common.utils.ServerValue"%>
<%@taglib uri="/WEB-INF/tld/pageutil.tld" prefix="pu" %>

<script src="/js/grid.locale-en.js" type="text/javascript"></script>
<script src="/js/jquery.jqGrid.min.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript" charset="UTF-8" src="<%=ServerValue.getMidContextPath()%>/js/yaodian100.common.js"></script>
<script type="text/javascript" charset="UTF-8" src="/js/jquery.cascade.ext.js"></script>
<script type="text/javascript" charset="UTF-8" src="/js/jquery.cascade.js"></script>
<script type="text/javascript" charset="UTF-8" src="/js/jquery.templating.js"></script>
<script type="text/javascript" charset="UTF-8" src="/js/jquery.alphanumeric.js"></script>
<script type="text/javascript" charset="UTF-8" src="/js/jquery.form.js"></script>

<link rel="stylesheet" type="text/css" media="screen" href="/css/ui.jqgrid.css" />
<link href="/css/jquery-ui-1.7.2.custom.css" rel="stylesheet" type="text/css" media="screen" />
<link href="/css/ddaccordion.css" rel="stylesheet" type="text/css" media="screen" />
<style type="text/css">
.msg{float:left; line-height:1em; margin:0; display:block;border:1px solid #f66;padding:2px 5px;*padding:2px 5px 1px;}
.msg.rn{background-color:#fff2f2;border-color:#f66;}
</style>
<s:if test="hasActionErrors()">
	<p><span class="msg rn"><s:actionerror/></span></p>
</s:if>
<s:fielderror />
<s:url var="memberPops" value="/json/memberPops.do?id=member"/>
<s:url var="memberAddressPops" value="/json/memberAddressPops.do?id=member_id&cartId=cart_id" escapeAmp="false"/>
<s:url var="productPops" value="/json/productPops.do"/>

<script>
$().ready( function() {
	$("#productId").numeric();
	$("input[id^='qty_']").numeric();	
	$("#shipfare").numeric();
	$("#shipfare2").html($("#shipfare").val());
	$("#loadingData").dialog({
	  title: '资料载入中',
		bgiframe: true,
		autoOpen: false,
		height: 150,
		width:280,
		modal: true
	});		

	$("#paytype30").attr("disabled",true);
	$("#paytype60").attr("disabled",true);
	if ($("#paytype30").attr("checked")==true && $("#paytype30").attr("disabled")==false ){
     	$("#allowSplitY").attr("disabled",true); //cod不允许拆单
     	$("#allowSplitY").attr("checked",false);
     	$("#allowSplitN").attr("checked",true); 
	}else{
		$("#allowSplitY").attr("disabled",false); //cod允许拆单
		$("#allowSplitY").attr("checked",true);
	    $("#allowSplitN").attr("checked",false);
	}
    
	$("#district").change(function() {
		//initWallet();
		//判断是否可货到付款
		var tmpCity=$("#city").find('option:selected').val();
		var tmpDistrict=$("#district").find('option:selected').text();
		if(tmpDistrict.substring(0,1)=='※' && "${canUseCod}" == "true"){
			$("#paytype30").attr("disabled",false); 
			$('#paytype60').attr('disabled', false);
			$("#showOrderPriceLimit").html("(需加收手续费 "+codFee+" 元。)");
		}	
		doFunc('update', '');
		//specialMessage();
	});
	var tmpDistrict=$("#district").find('option:selected').text();
	if(tmpDistrict.substring(0,1)=='※' && "${canUseCod}" == "true"){
		$("#paytype30").attr("disabled",false); 
		$("#paytype60").attr("disabled",false); 
		$("#showOrderPriceLimit").html("(需加收手续费 "+codFee+" 元。)");
	}	
	if(parseFloat($("#editTotalAmount").html())>10000 || "${canUseCod}" == "false"){
		$("#paytype30").attr("disabled",true);
		$("#paytype30").attr("checked",false); 
		$("#paytype60").attr("disabled",true);
		$("#paytype60").attr("checked",false); 
		$("#showOrderPriceLimit").html("(订单金额超过10000元，将不提供货到付款服务。)");
		if ( "${canUseCod}" == "false"){
			$("#showOrderPriceLimit").html("(订单中有商品不支持货到付款服务。)");
		}
	}

	//耀点100货到付款支援区域
	$("#cssPayArrive").click(function(){
		doAR('/pages/CART/step02_pay_arrive.html', 'dialog'); 
		openDialog('耀点100货到付款支援区域',content, 700, 700);
		//openDialog("耀点100货到付款支援区域",$("#divPayArrive").load("/pages/CART/step02_pay_arrive.html"),700,700);			
	});

	//耀点100运费计算标准
	$("#payPortage").click(function(){
		doAR('/pages/CART/step02_pay_portage.html', 'dialog'); 
		openDialog('耀点100运费计算标准',content, 700, 360);
		//openDialog("耀点100运费计算标准",$("#divPayPortage").load("/pages/CART/step02_pay_portage.html"),700,360);			
	});

	<%--发票信息--%>
	$("#invotype01").attr("checked",true); 
	$("#invoTitle").hide();
	
	$('#invotype01').click(function(){
		$("#invoTitle").val("");
		$("#invoTitle").hide();
	});
	$('#invotype02').click(function(){
		$("#invoTitle").show();
	});

	 $('input[id^=paytype]').click(function(){
	    	if ($('input[id=paytype30]').is(":checked") == true){
		     	$("#allowSplitY").attr("disabled",true); //cod不允许拆单
		     	$("#allowSplitY").attr("checked",false);
		     	$("#allowSplitN").attr("checked",true); 
	    	}else{
	    		$("#allowSplitY").attr("disabled",false);
		    }
	    });
	    
	$("#getMember").click(function() {
		qry_target = 'member';
		doAR('${memberPops}', 'dialog'); 
		openDialog('会员搜寻',content, 600, 440);
	});
	$("#addProduct").click(function() {
		if($("#productId").val()=="请输入商品编号"){
			alert("商品编号未填寫");
			$("#productId").focus();
			return false;
		}
		modifyProduct('add',$("#productId").val());
	});
	$("#getAddress").click(function() {
		doAR('${memberAddressPops}', 'dialog'); 
		openDialog('地址簿搜寻',content, 650, 440);
	});
	$("#reload").click(function() {
		modifyProduct('update', '');
	});
	$("#confirmMember").click(function() {
		$("#formObj").attr("action","updateMember.do");
		doFunc('confirm', '');
	});
	$("#confirmCart").click(function() {
		$("#formObj").attr("action","update.do");
		doFunc('confirm', '');
	});

	$("#confirmCart").click(function() {
		$("#formObj").attr("action","update.do");
		doFunc('confirm', '');
	});

	$("#payCart").click(function() {
		$("#formObj").attr("action","pay.do");

		if($("#inv_name").val()==''){
			alert("请输入收货人姓名");
			$("#inv_name").focus();
			return false;
		}
		if($("#province").val()=='' || $("#city").val()=='' || $("#district").val()=='' || $("#inv_addr").val()==''){
			alert("请输入收货地址");
			return false;
		}

	
		if($("#zipCode").val()==''){
			alert("请输入收货地址邮编");
			$("#zipCode").focus();
			return false;
		}
		if($("#shipfare").val()==''){
			alert("请输入运费");
			$("#shipfare").focus();
			return false;
		}
		if($("#inv_mobile").val()=='') {
			// || ($("#inv_areaCode").val()=='' && $("#inv_phone").val()==''))){
			if($("#inv_areaCode").val()=='') {
				alert("请输入收货人电话");
				$("#inv_areaCode").focus();
			}
			if($("#inv_phone").val()=='') {
				alert("请输入收货人电话");
				$("#inv_phone").focus();
			}
			return false;
		}
		if($("#paytype10").attr("checked")==true||$("#paytype20").attr("checked")==true||$("#paytype30").attr("checked")==true||$("#paytype50").attr("checked")==true || $("#paytype60").attr("checked")==true || $("#paytype70").attr("checked")==true){
			// pass
		} else {
			alert("请选择付款方式");
			$("#paytype20").focus();
			return false;
		}
		if(($("#paytype30").attr("checked")==true || $("#paytype60").attr("checked")==true) && $("#inv_mobile").val()==''){
			alert("货到付款, 手机为必填");
			$("#inv_mobile").focus();
			return false;
		}

		$("#zipCode").numeric();
		$("#mobile").numeric();
		$("#areaCode").numeric();
		$("#phone").numeric();
		$("#extension").numeric();
		
		doFunc('buy', '');
	});

	$(':input[name="paymentTp"]').each(function(){
		$(this).click(function(){
			if($(this).attr('value')=='30' || $(this).attr('value')=='60'){
				$('#codFee').html('+ COD手续费 '+codFee);
				$('#totalAmount').html(totalAmountWithoutCod+codFee);
			}else{
				$('#codFee').html('');
				$('#totalAmount').html(totalAmountWithoutCod);
			}
		});
	});
	if('${param.paymentTp}'=='30' || '{param.paymentTp}'=='60'){
		$('#codFee').html('+ COD手续费 '+codFee);
		$('#totalAmount').html(totalAmountWithoutCod+codFee);
	}
})
${pu:listAdd('paramsCod', 'Freight.key')}
${pu:listAdd('paramsCod', 'COD')}

${pu:reqSet('codFee', pu:queryByHql('from Option where menu.key=? and code=?', pu:arrayGet('paramsCod'), null))}
var codFee=<fmt:formatNumber value="${codFee[0].memo1}" pattern="0.0#"/>;
var totalAmountWithoutCod=<fmt:formatNumber value="${cart.shipfare+cart.amount}" pattern="0.0#"/>;
function modifyProduct(func, id) {
	$('#formObj').attr('action','update.do');
	$("#function").val(func);
	$("#objId").val(id);
	$("#formObj").submit();
}
function doFunc(func, id) {
	$("#function").val(func);
	$("#objId").val(id);
	$("#formObj").submit();
}
function compositeCampaign(title, desc, detail, startDate, endDate, url, dialogId){
	if(url!='' && url!='null'){
		eventUrl='<p><a href="'+url+'"><strong>&gt;&gt; 看活动网页</strong></a></p>';
	}else{
		eventUrl='';
	}
		
	var campaignContent='<div class="promo-popup">'+ 
	  '<h2>'+title+'</h2>'+
	
	'<p>'+detail+'</p>'+

	'<p class="d-line">&nbsp;</p>'+
	'<h3>时间：</h3>'+
	'<p>'+startDate+' ~ '+endDate+'</p>'+

	eventUrl+


	'<p class="d-line">&nbsp;</p>'+
	'<h3>活动说明：</h3>'+
	desc+
	'<p align="center"><a href="javascript:closeDialog(\''+dialogId+'\');" class="btn-mid">关闭</a></p>'+
	'</div>';
	return campaignContent;
	}
var content;
var qry_target = '01';

/**
 * 电话订购-重设地址下拉选单
 * @param sel_province
 * @param sel_city
 * @param sel_district
 * @return
 */
function resetPhonShopAddress(sel_province, sel_city, sel_district) {
	$.ajax({
		beforeSend: function(){
			$("#loadingData").dialog("open");
			$("#province").children().each(function(index){
				if (trim($(this).text()) == trim(sel_province)){
					$("#province")[0].selectedIndex = index;
				}
			});
		  $("#city").html("<option value='" + sel_city + "'>" + sel_city + "</option>");  
		  $("#district").html("<option value='" + sel_district + "'>" + sel_district + "</option>");
		},	
		type:　"post",
		url:　"/ecadmin/cs/tuangouShop/update.do",
		cache: false,
		data:　"function=updAddr&cart.receiverName=" + $("#inv_name").val()
		+ "&cart.receiverProvince=" + sel_province + "&cart.receiverCity=" + sel_city
		+ "&cart.receiverArea=" + sel_district + "&cart.receiverZip=" + $("#zipCode").val()
		+ "&cart.receiverAddr=" + $("#inv_addr").val() + "&cart.receiverMobile=" + $("#inv_mobile").val()
		+ "&cart.receiverPhoneArea=" + $("#inv_areaCode").val() + "&cart.receiverPhone=" + $("#inv_phone").val()
		+ "&cart.receiverExt=" + $("#inv_extension").val(),
		success:　function(){
			location.href= "/ecadmin/cs/tuangouShop/update.do?function=updAddr";
			$("#loadingData").dialog("close");
		}
	}); 
}
</script>
<br /><div style="color:red">
<s:actionerror />
<s:fielderror /></div>
<h1>团购订购</h1>
<s:form method="post" id="formObj" name="tuangouShop" action="update.do">
<s:hidden name="step" />
<s:hidden name="function" id="function"/>
<s:hidden name="objId" id="objId"/>
	<table class="tb-data" width="100%">
		<tr>
			<th width="150px">会员</th>
			<td width="650px">
<c-rt:if test="${empty member}">
	<s:textfield name="memberId" id="member_id"/>
	<img class="ui-icon ui-icon-search" src="/images/none.gif" style="height:16px; width:16px; position:relative; display:inline;" 
		id="getMember"/>
	<input type="button" id="confirmMember" value="确认">
</c-rt:if><c-rt:if test="${!empty member}">
	<s:hidden name="memberId" id="member_id"/>
	<div>
	登入代码 <span>${member.loginId}</span>,会员编号 <span>${member.memberId}</span>, 邮件 <span id="member_email">${member.email}</span>, 手机 <span id="member_mobile">${member.mobile}</span>
	</div>
</c-rt:if>
			</td>
		</tr>
		<tr>
			<th>商品<br/>
			<c-rt:if test="${chkScm ne 'Y'}">
			<span class="txt-gy"><s:textfield name="productId" id="productId" size="15" value="请输入商品编号" style="color:#888" onblur="if(this.value=='') {this.value='请输入商品编号';this.style.color='#aaa';this.style.background='#FFDFDF'}" onfocus="if(this.value=='请输入商品编号') {this.value='';}this.style.color='#000';"/></span><INPUT type="button" id="addProduct" value="增加"/>
			</c-rt:if>
			<td>
			<s:if test="hasActionMessages()">
				<p><span class="msg rn"><s:actionmessage/></span></p>
			</s:if>
			<table id="cartOrder" width="800px">
			<thead>
			<tr>
				<th width="40px">动作</th>
				<th>编号</th>
				<th>名称</th>
				<th>规格</th>
				<th>数量</th>
				<th>单价</th>
				<th>金額</th>
				<th>重量(g)</th>
				<th>库存</th>
			</tr></thead>
			<tbody>
<s:set name="copCnt" value="0" />
<s:iterator value="cart.cartOrderProducts" var="product" status="status1">
<c-rt:if test="${detail.detailTp=='2'}"><%-- 计算主商品位置 --%>
<s:set name="copCnt" value="%{#copCnt+1}" />
</c-rt:if>
<s:iterator value="%{#product.details}" var="detail" status="status2">
			<tr>
				<td>
				<INPUT onclick="$('#formObj').attr('action','update.do');modifyProduct('remove', '${detail.prodSpecId}')" type="button" value="删除"/>
				</td>
				<td>${detail.prodId}</td>
				<td>${detail.prodName}</td>
				<td>
				<s:set name="specListByProd" value="specMap[#detail.prodId]"/>
				<s:select name="specList[%{#status1.index}]" list="#specListByProd" listKey="value.specificationId" listValue="value.specificationName" onchange="modifyProduct('update', '%{#copCnt};%{#status2.index}')"></s:select>
				</td>
				<td><s:textfield name="qtyList" size="2" value="%{#detail.qty}" id="qty_%{#detail.prodId}" onblur="if(this.value==''){alert('请输入数量');this.focus();}else{modifyProduct('update', '%{#status1.index};%{#status2.index}')}"/></td>
				<td><s:textfield name="amountList" id="productamount_%{#detail.prodId}" onblur="if(this.value.match(/^\d*\.?\d{0,1}$/)==null){alert('商品单价为必填且应为最多只能保留一位小数点的数字');this.focus();}else{modifyProduct('update', '%{#status1.index};%{#status2.index}')}" size="5" maxlength="10" value="%{#detail.amount}"/></td>
				<td>${product.amount}</td>
				<td>${detail.weight}</td>
				<td>${specInvMap[detail.prodId][detail.prodSpecId].inventory}</td>
			</tr>
			</s:iterator></s:iterator>
			</tbody>
			</table>
			</td>
		</tr>
<c-rt:if test="${!empty cart}">
	<s:hidden name="cartId" id="cart_id"/>
		<tr>
			<th>运送信息 
			<br/><INPUT id="getAddress" type="button" value="由地址簿选取"/>
			</th>
			<td>
			<table id="shipping" width="800px">
			<tr>
				<th>姓名</th>
				<td><s:textfield name="cart.receiverName" id="inv_name" size="20"/></td>
			</tr>
			<tr>
				<th>地址</th>
				<td>
				省份：<select id="province" name="cart.receiverProvince" class="c-prov" onchange="doFunc('update', '');">
						<option value="">== 选择省 ==</option>
						<c-rt:forEach items="${provincesMap}" var="province" >
							<option value="${province.key}" ${cart.receiverProvince eq province.key ? 'selected="selected"' : '' }>${province.key}</option>
						</c-rt:forEach>
						</select>
				市：<select id="city" name="cart.receiverCity" onchange="doFunc('update', '');">
				<option value="">== 选择城市 ==</option>
				<c-rt:forEach items="${citysMap}" var="city" >
					<option value="${city.key}" ${cart.receiverCity eq city.key ? 'selected="selected"' : ''}>${city.key}</option>
				</c-rt:forEach>
				</select>
				区：<select id="district" name="cart.receiverArea" onchange="doFunc('update', '');">
				<option value="">== 选择地区 ==</option>
				<c-rt:forEach items="${districts}" var="district" >${district.isCod }
					<c-rt:choose>
						<c-rt:when test="${district.isCod eq 'Y'}">
							<c-rt:set var="result">${district.toDistrict},※${district.toDistrict},${district.isPos},${district.version}</c-rt:set>
						</c-rt:when>
						<c-rt:otherwise>
							<c-rt:set var="result">${district.toDistrict},${district.toDistrict},${district.isPos},${district.version}</c-rt:set>
						</c-rt:otherwise>
					</c-rt:choose>
					<option value="${district.toDistrict}" ${fn:split(result,',')[0] eq cart.receiverArea ? 'selected="selected"' : ''}>${fn:split(result,",")[1]}</option>
				</c-rt:forEach>
				
				</select><br/>
				邮编： <s:textfield name="cart.receiverZip" id="zipCode" size="6" maxlength="6"/>
				 街道： <s:textfield size="50" cssClass="txt-gy" name="cart.receiverAddr" id="inv_addr" />(输入街道地址，例如：和平路12巷52号)
				</td>
			</tr>
			<tr>
				<th>电话</th>
				<td>
				固定 <s:textfield name="cart.receiverPhoneArea" id="inv_areaCode" size="5" maxlength="4"/>-
		    		<s:textfield name="cart.receiverPhone" id="inv_phone" size="10" maxlength="10" />- 分机
 					<s:textfield name="cart.receiverExt" id="inv_extension" size="4" maxlength="8"/>
 				 <br/>
				手机 <s:textfield name="cart.receiverMobile" id="inv_mobile" size="18" maxlength="11"/>
				</td>
			</tr>
			<tr>
				<th>备注</th>
				<td><textarea name="cart.memo" cols="80" rows="5"></textarea></td>
			</tr>
			<tr>
				<th>运费</th>
				<td>
				<strong>运送方式：</strong>一般快递或EMS邮政快递<br/>
				<strong>运费：<span class="txt-rd"><s:textfield id="shipfare" name="shipfare" size="5" maxlength="5" onblur="if(this.value==''){alert('请输入运费');this.focus();}else{doFunc('update', '')};"/></span>元</strong>(重量总计<fmt:formatNumber value="${cart.weightSum}" pattern="0.000"/>kg，<a href="javascript:return false;" id=payPortage>查看运费计算方式</a>)
				</td>
			</tr>
			</table>
		</tr>
			<c:if test="${fn:length(cart.cartOrderProducts)>1}"><%-- 提供选择是否允许拆单 --%>
			<tr>
				<th>商品缺货配送处理方法</th>
				<td>
					<div class="discount-way">
						<ul>
							<li class="w-1of1"><label><input name="allowSplit" type="radio" id="allowSplitY" value="Y"/> <strong>有货先发</strong>（若订单中部分商品缺货，优先配送有货商品，订单将会被拆分成多张订单，总订单金额不变，<span class="txt-rd">不支持货到付款</span>）</label></li>
							<li class="w-1of1 pad"><label><input name="allowSplit" type="radio" id="allowSplitN" value="N"/> <strong>货齐再发</strong>（若订单中部分商品缺货，则会等到商品补齐再配送）</label></li>
						</ul>
					</div>
				</td>
			</tr>
	    </c:if>
		<tr>
			<th>发票信息</th>
			<td>
				<input id="invotype01" name="cart.invoiceTp" type="radio" value="01">  <strong>个人</strong>
		 		<input id="invotype02" name="cart.invoiceTp" type="radio" value="02">  <strong>单位</strong> 
		 		<input size="20" type="text" name="cart.invoiceTitle" id="invoTitle" value="" maxlength="40"/> 
			</td>
		</tr>
		<tr>
			<th>付款金额</th>
			<td>商品 <span id="editTotalAmount"><fmt:formatNumber value="${cart.amount+cart.discount}" pattern="0.0#"/></span> + 运费 <fmt:formatNumber value="${cart.shipfare}" pattern="0.0#"/> <span id="codFee"></span> = <span id="totalAmount"><fmt:formatNumber value="${cart.shipfare+cart.amount}" pattern="0.0#"/></span></td>
		</tr>
		<tr>
			<th>付款方式</th>
			<td>
				<div><input id="paytype20" name="paymentTp" type="radio" value="20"<c-rt:if test="${paymentTp=='20'}"> checked</c-rt:if>> <strong>邮局汇款</strong> <span class="txt-gy">(至邮局柜台汇款)</span></div>
				<div><input id="paytype10" name="paymentTp" type="radio" value="10"<c-rt:if test="${paymentTp=='10'}"> checked</c-rt:if>> <strong>银行转帐</strong> <span class="txt-gy">(至银行柜台汇款)</span></div>
				<div><input id="paytype30" name="paymentTp" type="radio" value="30"<c-rt:if test="${paymentTp=='30'}"> checked</c-rt:if>>  <strong>货到付款(现金)</strong> <span class="txt-gy"></span>
				<%-- 電話訂購目前不需支持 POS機刷卡方式
				<input id="paytype60" name="paymentTp" type="radio" value="60"<c-rt:if test="${paymentTp=='60'}"> checked</c-rt:if>>  <strong>货到付款(POS)</strong> <span class="txt-gy">(<a href="javascript:return false;" class="cssPayArrive" id="cssPayArrive">查看支援地区</a>)</span>
				--%>
				<span id="showOrderPriceLimit"> </span>
				</div>
				<div><input id="paytype50" name="paymentTp" type="radio" value="50"<c-rt:if test="${paymentTp=='50'}"> checked</c-rt:if>> <strong>网上支付</strong><span class="txt-gy">(支付宝，快钱，银联卡，财付通)</span></div>
				<div><input id="paytype70" name="paymentTp" type="radio" value="70"<c-rt:if test="${paymentTp=='70'}"> checked</c-rt:if>> <strong>信用卡单期支付</strong><span class="txt-gy">(<a href="http://www.yaodian100.com/help/5_online.html" target="_blank">查看支持銀行</a>)</span></div>
			</td>
		</tr></c-rt:if>
		<tr>
			<th></th>
			<td>
			<input type="button" id="payCart" value="送出" /> <s:action name="/cs/tuangouShop/input" var="inputUrl" /> 
			<input type="reset" value="重设" /></td>
		</tr>
	</table>
</s:form>
<div id="loadingData" style="display:none;">
	<img src="/images/loading.gif"/>资料载入中,请稍候...
</div>